package com.kedacom.ctsp.authority.service.simple;


import com.google.common.collect.Lists;
import com.kedacom.ctsp.authority.entity.DepartmentForTree;
import com.kedacom.ctsp.authority.service.DepartmentForTreeService;
import com.kedacom.ctsp.web.entity.TreeSupportBean;
import com.kedacom.ctsp.web.service.simple.AbstractTreeSortService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;


/**
 * 默认的服务实现
 *
 */
@Service("departmentForTreeService")
public class DepartmentForTreeServiceImpl
        extends AbstractTreeSortService<DepartmentForTree, String> implements DepartmentForTreeService {


    @Override
    public List<DepartmentForTree> convertToTree(List<DepartmentForTree> nodes) {
        if (CollectionUtils.isEmpty(nodes)) {
            return Lists.newArrayList();
        }
        Set<String> nodeIds = nodes.stream().map(DepartmentForTree::getId).collect(Collectors.toSet());

        // 设置parentId, 如果不为顶层,但是又是根节点

        // 转换为树形结构
        List<DepartmentForTree> results = TreeSupportBean.list2tree(nodes, DepartmentForTree::setChildren,
                (Predicate<DepartmentForTree>) entity -> isCurRootNode(entity, nodeIds));
        return results;
    }

    /**
     * 是否为当前根节点
     * 1.是顶层
     * 2.不是顶层, 但是 是根节点
     *
     * @return
     */
    private boolean isCurRootNode(DepartmentForTree department, Set<String> nodeIds) {
        // 是顶层
        if (department.getParent() == null || department.getParent().getId() == null) {
            return true;
        }

        // 不是顶层, 但是 是根节点
        return !nodeIds.contains(department.getParent().getId());
    }
}
